<template>
  <view class="resume-container" :style="{ paddingTop: totalNavHeight + 'px' }">
      <!-- 自定义导航栏 -->
      <CustomNavBar ref="navBarRef" :show-logo="true" />
    
    <!-- 标题区域 -->
    <view class="title-bar">
      <text class="title-text">我的简历库</text>
    </view>
    
    <!-- 未登录状态 -->
    <view v-if="!isLogin" class="login-prompt">
      <view class="login-card" @tap="goToLogin">
        <view class="login-content">
          <image class="login-avatar" src="/static/logo.png" mode="aspectFill"></image>
          <view class="login-info">
            <text class="login-title">立即登录</text>
            <text class="login-subtitle">登录后查看您的简历库</text>
          </view>
          <text class="login-arrow">›</text>
        </view>
      </view>
 
    </view>
    
    <!-- 已登录状态 -->
    <view v-else>
      <!-- 简历卡片列表 -->
      <scroll-view 
        class="resume-list" 
        scroll-y="true"
        show-scrollbar="false"
        enhanced="true"
        bounces="true"
      >
        <!-- 我的资料卡片项 -->
        <view class="resume-card" @tap="handleViewProfile">
          <view class="resume-info">
            <image class="avatar" :src="getAvatarUrl()" mode="aspectFill"></image>
            <view class="resume-detail">
              <text class="resume-name">{{userInfo['68a6b776096ba6d65c500839'] || ''}}</text>
              <text class="resume-location">{{userInfo['68b8f95c8326c4bbc62df659'] || ''}}</text>
            </view>
          </view>
          <view class="resume-action">
            <text class="arrow-right">›</text>
          </view>
        </view>
        
        <!-- 添加简历卡片 -->
        <view class="add-resume-card" @tap="handleAddResume">
          <text class="add-text">+添加简历库</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import CustomNavBar from '/pages/components/CustomNavBar.vue'
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
import { apiService, ApiService } from '/pages/utils/api.js'
import { useUserStore } from '/pages/store/user.js'

const platform = ref()

const userStore = useUserStore()

const permission = ref(false)

const isLogin = ref(false)

const userInfo = ref({})
// 导航栏组件引用
const navBarRef = ref(null)

// 计算总的导航栏高度（添加一些额外的间距）
const totalNavHeight = computed(() => {
  try {
    // 确保组件已挂载且存在
    if (navBarRef.value && navBarRef.value.totalNavHeight) {
      // totalNavHeight 是一个 computed，需要访问 .value
      const height = typeof navBarRef.value.totalNavHeight === 'object' 
        ? navBarRef.value.totalNavHeight.value 
        : navBarRef.value.totalNavHeight
      return height + 20  // 添加20px的间距
    }
    return 44 + 20  // 默认高度
  } catch (error) {
    console.warn('获取导航栏高度失败，使用默认值:', error)
    return 44 + 20  // 默认高度
  }
})

const goToTest = () => {
  uni.navigateTo({
    url: '/pages/qrcode/qrcode'
  })
}

// 获取头像URL的方法
const getAvatarUrl = () => {
  const avatarData = userInfo.value['68b8f69a8326c4bbc62df3d8']
  if (avatarData && avatarData.trim() !== '') {
    try {
      const parsedAvatar = JSON.parse(avatarData)
      // 检查是否是数组且包含文件信息
      if (Array.isArray(parsedAvatar) && parsedAvatar.length > 0) {
        const fileInfo = parsedAvatar[0]
        // 优先使用 original_file_full_path，如果没有则使用 file_path + file_name
        return fileInfo.original_file_full_path || 
               (fileInfo.file_path + fileInfo.file_name) || 
               '/static/logo.png'
      }
      return '/static/logo.png'
    } catch (error) {
      console.error('解析头像失败:', error)
      return '/static/logo.png'
    }
  }
  return '/static/logo.png'
}

// 添加简历方法
const handleAddResume = () => {
  uni.navigateTo({
    url: '/pages/tabs/profile/resume'
  })
}

// 跳转到登录页面
const goToLogin = () => {
  uni.navigateTo({
    url: '/pages/login/login'
  })
}

// 查看我的资料
const handleViewProfile = () => {
  uni.navigateTo({
    url: '/pages/tabs/profile/myProfile'
  })
}

// 刷新用户信息（强制从API获取）
const refreshUserInfo = async () => {
  try {
    console.log('强制刷新用户信息')
    const response = await apiService.getUserInfo({
      userRowid: userStore.rowid
    })
    
    const apiUserInfo = JSON.parse(response.data)
    console.log('API获取的最新用户信息:', apiUserInfo)
    
    // 更新本地存储
    uni.setStorageSync('userInfo', apiUserInfo)
    console.log('用户信息已更新到本地')
    
    // 更新页面数据
    userInfo.value = apiUserInfo
    console.log('userInfo:', userInfo.value['68a6b776096ba6d65c500839'])
    
    uni.showToast({
      title: '用户信息已更新',
      icon: 'success'
    })
    
  } catch (error) {
    console.error('刷新用户信息失败:', error)
    uni.showToast({
      title: '刷新用户信息失败',
      icon: 'none'
    })
  }
}

// 检测平台
const checkPlatform = () => {
  try {
     const { uniPlatform } = uni.getSystemInfoSync();
    console.log('platform', uniPlatform);
    
    platform.value = uniPlatform
    
    // 根据平台执行不同逻辑
    if (uniPlatform === 'mp-weixin') {
      console.log('当前运行在微信小程序')
      // 微信小程序特定逻辑
    } else if (uniPlatform === 'app') {
      console.log('当前运行在APP端')
      // APP端特定逻辑
    } else if (uniPlatform === 'h5') {
      console.log('当前运行在H5端')
      // H5端特定逻辑
    }
  } catch (error) {
    console.error('获取系统信息失败:', error)
  }
}

const getUserInfo = async () => {
 const response = await apiService.getUserInfo(userStore.rowid)

    if(response && response.rows && response.rows.length > 0) {
    
    const apiUserInfo = response.rows[0]
    console.log('API获取的用户信息:', apiUserInfo)
    
    // 将用户信息存储到本地
    uni.setStorageSync('userInfo', apiUserInfo)
    console.log('用户信息已存储到本地')

    userStore.updateUserInfo(apiUserInfo)
    userStore.setRowid(apiUserInfo.rowid)

    userInfo.value = apiUserInfo

    }
}

onLoad(() => {
  console.log('userInfo', userStore.userInfo);
  console.log('onLoad');
  console.log('userStore.isLogin', userStore.isLogin);
  checkPlatform()
  if(userStore.isLogin){
    userInfo.value = userStore.userInfo
    isLogin.value = userStore.isLogin
    console.log('isLogin', isLogin.value);
    
  }else{

  }


 
})

onShow(() => {
  
  // 监听刷新用户信息事件
  uni.$on('refreshUserInfo', async () => {
    console.log('收到refreshUserInfo事件，刷新用户信息');
   await getUserInfo()
     if(userStore.isLogin){
    userInfo.value = userStore.userInfo
    isLogin.value = userStore.isLogin
    console.log('isLogin', isLogin.value);
    
  }
  })

})

// 页面卸载时清理事件监听
onUnload(() => {
  console.log('页面卸载，清理事件监听');
  uni.$off('refreshUserInfo')
})
</script>

<style scoped>
.resume-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 0 10rpx;
  margin-top: -1px; /* 消除可能的顶部间隙 */
}

/* 未登录状态样式 */
.login-prompt {
  padding: 0 10rpx;
  margin-top: 20rpx;
}

.login-card {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.login-card:active {
  transform: scale(0.98);
  box-shadow: 0 1rpx 5rpx rgba(0, 0, 0, 0.1);
}

.login-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.login-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
  background-color: #f5f5f5;
}

.login-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.login-title {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 8rpx;
}

.login-subtitle {
  font-size: 24rpx;
  color: #999;
}

.login-arrow {
  font-size: 40rpx;
  color: #ccc;
  margin-left: 20rpx;
}

/* 标题区域 */
.title-bar {
  padding: 20rpx 0;
  position: relative;
  margin: 20rpx 0;
}

.title-bar::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 8rpx;
  height: 28rpx;
  background-color: #FF6B9B;
  border-radius: 4rpx;
}

.title-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  padding-left: 24rpx;
}

.resume-list {
  padding: 20rpx 0;
  height: calc(100vh - 200rpx); /* 为scroll-view设置固定高度 */
  box-sizing: border-box;
}

.resume-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.resume-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.resume-detail {
  display: flex;
  flex-direction: column;
}

.resume-name {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 8rpx;
}

.resume-location {
  font-size: 24rpx;
  color: #999;
}

.resume-action {
  color: #ccc;
}

.arrow-right {
  font-size: 56rpx;
  color: #ccc;
  font-weight: 300;
  transform: scaleY(1.5);
}

.add-resume-card {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 40rpx 0;
  margin-top: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.add-text {
  font-size: 28rpx;
  color: #999;
}
</style>